﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ESupervision.Models;
using ESupervision.ViewModels;
using Microsoft.AspNet.Identity;

namespace ESupervision.Controllers
{
    [Authorize]
    public class DocumentController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: /Document/
        [Authorize(Roles = "Student")]
        public async Task<ActionResult> Index(string searchString)
        {


            string userId = User.Identity.GetUserId();
            var student = db.Students.Find(userId);
            var documents = from b in db.Documents
                            where b.CreatedByUserId == userId || b.CreatedByUserId == student.SupervisorUserId || b.CreatedByUserId == student.SecondMarkerUserId
                            select b;
            documents.Include(d => d.AttachmentFile).Include(d => d.CreatedByUser);
            if (!String.IsNullOrEmpty(searchString))
            {
                documents = documents.Where(d => d.AttachmentFile.FileName.Contains(searchString));

            }
            return View(await documents.ToListAsync());
        }
        [Authorize(Roles = "Teacher")]
        public ActionResult TeacherIndex(string searchString)
        {
            TeacherIndexVM teacher = new TeacherIndexVM();
            string userId = User.Identity.GetUserId();
            var staicTeacher = db.Teachers.Find(userId);
            var documents = from b in db.Documents
                            where b.CreatedByUserId == userId
                            select b;
            documents.Include(d => d.AttachmentFile).Include(d => d.CreatedByUser);
            teacher.Documents = documents.ToList();
            //list student
            teacher.Students = (from s in db.Students
                                where s.SupervisorUserId == userId || s.SecondMarkerUserId == userId
                                select s).ToList();
            if (!String.IsNullOrEmpty(searchString))
            {
                teacher.Students = teacher.Students.Where(s => s.LastName.Contains(searchString)
                                       || s.FirstName.Contains(searchString)).ToList();
            }
            return View(teacher);
        }

        // GET: /Document/Details/5

        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Document document = await db.Documents.FindAsync(id);


            if (document == null)
            {
                return HttpNotFound();
            }

            ViewBag.Document = document;

            String userId = User.Identity.GetUserId();

            Comment comment = new Comment
            {
                UserId = userId,
                DocumentID = document.DocumentID
            };

            return View(comment);
        }

        // GET: /Document/Create

        public ActionResult Create()
        {
            string userId = User.Identity.GetUserId();

            Document document = new Document
            {
                CreatedByUserId = userId,
                CreatedTime = DateTime.Now
            };
            return View(document);
        }

        // POST: /Document/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "DocumentID,CreatedByUserId,Subject,Body")] Document document, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var attachmentFile = new AttachementFile
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        attachmentFile.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    db.AttachmentFiles.Add(attachmentFile);
                    await db.SaveChangesAsync();
                    document.AttachmentFileID = attachmentFile.AttachementFileID;

                }
                document.CreatedTime = DateTime.Now;
                db.Documents.Add(document);
                await db.SaveChangesAsync();
                if (User.IsInRole("Teacher"))
                {
                    return RedirectToAction("TeacherIndex");
                }
                else
                {
                    return RedirectToAction("Index");
                }

            }
            return View(document);
        }
        // GET: /Document/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Document document = await db.Documents.FindAsync(id);
            if (document == null)
            {
                return HttpNotFound();
            }
            ViewBag.AttachmentFileID = new SelectList(db.AttachmentFiles, "AttachementFileID", "FileName", document.AttachmentFileID);
            ViewBag.CreatedByUserId = new SelectList(db.Students, "Id", "UserName", document.CreatedByUserId);
            return View(document);
        }

        // POST: /Document/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "DocumentID,CreatedByUserId,CreatedTime,Subject,Body,AttachmentFileID")] Document document)
        {
            if (ModelState.IsValid)
            {
                db.Entry(document).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            ViewBag.AttachmentFileID = new SelectList(db.AttachmentFiles, "AttachementFileID", "FileName", document.AttachmentFileID);
            ViewBag.CreatedByUserId = new SelectList(db.Students, "Id", "UserName", document.CreatedByUserId);
            return View(document);
        }

        // GET: /Document/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Document document = await db.Documents.FindAsync(id);
            if (document == null)
            {
                return HttpNotFound();
            }
            return View(document);
        }

        // POST: /Document/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            Document document = await db.Documents.FindAsync(id);
            db.Documents.Remove(document);
            await db.SaveChangesAsync();
            if (User.IsInRole("Teacher"))
            {
                return RedirectToAction("TeacherIndex");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]

        // public async Task<ActionResult> CreateComment([Bind(Include = "CommentID,UserId,CommentTime,Content,DocumentID")] DocumentComment documentcomment);

        public async Task<ActionResult> CreateComment([Bind(Include = "CommentID,UserId,CommentTime,Content,DocumentID")] Comment comment)
        {
            Document document = await db.Documents.FindAsync(comment.DocumentID);

            if (document == null)
            {
                return HttpNotFound();
            }

            ViewBag.Document = document;

            if (ModelState.IsValid)
            {
                comment.CommentTime = DateTime.Now;
                db.Comments.Add(comment);
                await db.SaveChangesAsync();
            }
            return RedirectToAction("Details/" + comment.DocumentID);
        }

        public ActionResult StudentDocuments(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var document = from d in db.Documents
                           where d.CreatedByUserId == id
                           select d;
            document.Include(d => d.AttachmentFile).Include(d => d.CreatedByUser);
            if (document == null)
            {
                return HttpNotFound();
            }

            return View(document);
        }
    }
}
